package com.shigen.demo.thread;

class Airconditioner {
    private int number = 0;

    public synchronized void increase() throws InterruptedException {
        // 多线程防止虚假唤醒，只能用while
        while (number != 0) {
            this.wait();
        }
        this.number++;
        System.out.println(Thread.currentThread().getName() + "~~" + number);
        this.notify();
}

    public synchronized void decrease() throws InterruptedException {
        if (number == 0) {
            this.wait();
        }
        this.number--;
        System.out.println(Thread.currentThread().getName() + "~~" + number);
        this.notify();
    }
}

public class ProducerAndConsumerDemo01 {
    public static void main(String[] args) {
        Airconditioner airconditioner = new Airconditioner();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airconditioner.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airconditioner.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        // new Thread(() -> {
        //     for (int i=0;i<10;i++){
        //         try {
        //             airconditioner.increase();
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // },"C").start();
        //
        // new Thread(() -> {
        //     for (int i=0;i<10;i++){
        //         try {
        //             airconditioner.decrease();
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // },"D").start();
    }
}
